package com.bjsxt.service.impl;

import com.bjsxt.mapper.RoleMapper;
import com.bjsxt.mapper.RoleMenuMapper;
import com.bjsxt.pojo.PageA;
import com.bjsxt.pojo.Role;
import com.bjsxt.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public PageA<Role> findAll(Integer page, Integer rows) {

        Page pg = PageHelper.startPage(page, rows);

        List<Role> list = roleMapper.selectAll();

        PageA<Role>  pga=new PageA<>(list,pg.getTotal());

        return pga;
    }

    @Override
    public Integer save(Role role,Integer[] mids) {
        Integer insert = 0;

        try {
            //添加角色实现
            insert = roleMapper.insert(role);
            //给当前角色赋予菜单实现
            for(Integer  mid:mids){
                roleMenuMapper.insert(role.getRid(),mid);
            }
            insert=1;
        } catch (Exception e) {
            throw  e;
        }

        return insert;
    }

    @Override
    public List<Integer> findMoreRM(Integer rid) {
        return roleMenuMapper.selectMore(rid);
    }

    @Override
    public Integer change(Role role, Integer[] mids) {

        int a =0;

        try {
            //[A]修改角色实现
            roleMapper.update(role);
            //[B]删除当前角色下所有菜单
            roleMenuMapper.delete(role.getRid());
            //[C]把新菜单赋予当前角色
            for(Integer mid:mids){
                roleMenuMapper.insert(role.getRid(),mid);
            }
            a=1;
        } catch (Exception e) {
            throw  e;
        }

        return a;
    }

    @Override
    public List<Role> findAll2() {
        return roleMapper.selectAll();
    }
}
